﻿using System;
using System.Linq;
using System.Text;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using NetEasyMusic.Lib.Models;
using Newtonsoft.Json;

namespace DevHub.WindowsApp.Dialogs;

public partial class SongDialog : UserControl
{
    private readonly SongModel _model;

    public SongDialog(SongModel model)
    {
        InitializeComponent();
        _model = model;
    }

    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        NameBlock.Text = _model.Name;
        IdBlock.Text = _model.Id;
        AlbumBlock.Text = _model.Album;
        AlbumIdBlock.Text = _model.AlbumId;
        SingerList.ItemsSource = _model.Artists.Select(x => new TextBlock() { Text = x.Name });
    }

    public void CopyInfo()
    {
        var builder = new StringBuilder();
        foreach (var artist in _model.Artists)
            builder.Append($"{artist.Name} ");

        var context = $"歌曲名: {_model.Name}{Environment.NewLine}" +
                      $"Id:    {_model.Id}{Environment.NewLine}" +
                      $"歌手:   {builder}{Environment.NewLine}" +
                      $"专辑名: {_model.Album}{Environment.NewLine}" +
                      $"专辑Id: {_model.AlbumId}";
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(context);
    }

    private async void CopyLyricClick(object? sender, RoutedEventArgs e)
    {
        var m = new NetEasyMusic.Lib.Data.Music("https://luckyfishneteasy.zeabur.app/", false);
        var lyric = await m.FindLyric(_model.Id);
        m.Dispose();
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(lyric);
    }

    private async void CopyCommentsClick(object? sender, RoutedEventArgs e)
    {
        var m = new NetEasyMusic.Lib.Data.Music("https://luckyfishneteasy.zeabur.app/", false);
        var commend = await m.GetCommend(_model.Id);
        m.Dispose();
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(JsonConvert.SerializeObject(commend));
    }
}